package com.rex.saas.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rex.saas.bean.request.DeviceLogRequest;
import com.rex.saas.db.entity.PaasDeviceOptLog;
import com.rex.saas.db.mapper.PaasDeviceOptLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DeviceOptLogService{
    @Autowired
    PaasDeviceOptLogMapper paasDeviceOptLogMapper;
    public IPage<PaasDeviceOptLog> selectPage(DeviceLogRequest deviceLogRequest, String tenantId) {
        Page<PaasDeviceOptLog> page = new Page<>(deviceLogRequest.getPageNo(), deviceLogRequest.getPageSize());
        LambdaQueryWrapper<PaasDeviceOptLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaasDeviceOptLog::getTenantId, tenantId);
        if(StringUtils.isNotBlank(deviceLogRequest.getDeviceName())){
            queryWrapper.eq(PaasDeviceOptLog::getDeviceName, deviceLogRequest.getDeviceName());
        }
        if(deviceLogRequest.getType()!=null){
            queryWrapper.eq(PaasDeviceOptLog::getType, deviceLogRequest.getType());
        }
        queryWrapper.between(PaasDeviceOptLog::getGmtCreate, DateUtil.parse(deviceLogRequest.getStartTime(), "yyyy-MM-dd HH:mm:ss"),
                DateUtil.parse(deviceLogRequest.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        return paasDeviceOptLogMapper.selectPage(page, queryWrapper);
    }

    public Integer count(DeviceLogRequest deviceLogRequest, String tenantId) {
        LambdaQueryWrapper<PaasDeviceOptLog> queryWrapper = new LambdaQueryWrapper<PaasDeviceOptLog>();
        queryWrapper.eq(PaasDeviceOptLog::getTenantId, tenantId);
        if(StringUtils.isNotBlank(deviceLogRequest.getDeviceName())){
            queryWrapper.eq(PaasDeviceOptLog::getDeviceName, deviceLogRequest.getDeviceName());
        }
        if(deviceLogRequest.getType()!=null){
            queryWrapper.eq(PaasDeviceOptLog::getType, deviceLogRequest.getType());
        }
        queryWrapper.between(PaasDeviceOptLog::getGmtCreate, deviceLogRequest.getStartTime(), deviceLogRequest.getEndTime());
        return paasDeviceOptLogMapper.selectCount(queryWrapper);
    }
}
